package org.mozhu.mboot.core.web.converter;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.util.Date;

public class String2DateConverter implements Converter<String, Date> {
	public final static String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss";
	public final static String DATE_FORMAT_PATTERN = "yyyy-MM-dd";

	@Override
	public Date convert(String source) {
		if (StringUtils.isBlank(source)) {
			return null;
		}
		try {
			return DateUtils.parseDate(source, DATE_TIME_FORMAT_PATTERN, DATE_FORMAT_PATTERN);
		} catch (ParseException e) {
			throw new IllegalStateException("Can't convert source[" + source + "] to date", e);
		}
	}
}
